# 导入相关库和模块
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from sqlalchemy.orm import Session
from database import SessionLocal
import sys
from admin.base_controller import BaseController
from config.logging import logger
from services.admin.sys_role_api_service import SysRoleApiService


# 定义获取数据库会话的依赖
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 定义控制器类
class SysRoleApi(BaseController):
    def __init__(self):
        super().__init__()
        self.router = APIRouter()

    async def lists(self, db: Session = Depends(get_db), roleName: str = Query(None), page: int = Query(default=1, ge=1),
                    limit: int = Query(default=20, ge=1)):
        """
        角色列表
        :param roleName:
        :param db:
        :param page:
        :param limit:
        :return:
        """
        service = SysRoleApiService(db)
        lists = await service.lists(page, limit, roleName)
        return self.success_response(data=lists, message="success")

    async def detail(self, roleId: int, db: Session = Depends(get_db)):
        """
        角色详情
        :param roleId:
        :param db:
        :return:
        """
        service = SysRoleApiService(db)
        result = await service.detail(roleId)
        return self.success_response(data=result, message="success")

    async def create(self, roleData: dict, request: Request, db: Session = Depends(get_db)):
        """
        创建角色
        :param roleData:
        :param db:
        :return:
        """
        service = SysRoleApiService(db)
        result = await service.create(roleData, request.state.user['id'])
        return self.success_response(data=result, message="success")

    async def update(self, roleId: int, roleData: dict, request: Request, db: Session = Depends(get_db)):
        """
        更新角色
        :param roleId:
        :param roleData:
        :param db:
        :return:
        """
        service = SysRoleApiService(db)
        result = await service.update(roleId, roleData, request.state.user['id'])
        return self.success_response(data=result, message="success")

    async def delete(self, roleId: int, db: Session = Depends(get_db)):
        """
        删除角色
        :param roleId:
        :param db:
        :return:
        """
        service = SysRoleApiService(db)
        result = await service.delete(roleId)
        return self.success_response(data=result, message="success")

# 使用
sys_role_api = SysRoleApi()
router = sys_role_api.router
